const jwt = require('jsonwebtoken');
const secret = process.env.JWT_SECRET;

// token 生成
function generateToken(user) {
  const payload = {
    id: user.id,
    username: user.username,
  };
  const token = jwt.sign(payload, secret, { expiresIn: '720h' });
  return token;
}

// 解析 token
function parseToken(token) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, secret, (err, result) => {
      if (err) resolve(false)
      const { id, username: user } = result
      resolve({ id, user })
    })
  })
}

module.exports = {
  generateToken,
  parseToken
}
